package com.fce.fcesystem.controller;

import com.fce.fcesystem.service.SendService;
import com.fce.fcesystem.service.serviceImp.UserServiceImpl;
import com.fce.fcesystem.utils.JsonResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wenzhuo
 * @create 2024-04-04 2024/4/4
 */
@RestController
@RequestMapping("message")
public class SendController extends BaseController{

    @Resource
    private SendService sendService;

    @Resource
    private UserServiceImpl userService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("/send")
    public JsonResult<String> code(@RequestParam("phone") String phone) {

        //根据号码判断用户是否存在
        if(userService.checkUserByPhone(phone) == null){
             return new JsonResult<>(USER_NOT_EXIT,"该手机的用户不存在！");
        }

        //判断redis中是否存在验证码
        String code = redisTemplate.opsForValue().get(phone);
        System.out.println(code);
        if (!StringUtils.isEmpty(code)) {
            return new JsonResult<>(KEY_ALRED_EXIT,"请不要重复发送验证码！");
        }
        //生成验证码存在redis中,截取前六位生成验证码
        code = UUID.randomUUID().toString().substring(0, 6);
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        param.forEach((k, v) -> System.out.println(k + " ==> " + v));
        Boolean isSend = sendService.send(phone, "SMS_205456105", param);

        if (isSend) {
            //发送成功存到redis中,设置过期时间
            redisTemplate.opsForValue().set(phone, code, 10, TimeUnit.MINUTES);
            return new JsonResult<>(OK,phone + ":" + code + "发送成功");

        } else {
            return new JsonResult<>(SMS_SEND_FAILED,phone + ":" + code + "发送失败");
        }
    }
}
